
#include <iostream>
#include <string>

#include "gameserver.h"
#include "functions.h"
#include "sbconstants.h"

#include "logmanager.h"


int main(int numArguments, char** arguments)
{
	LogManager::Initialize("server_log");

	// Read port
	unsigned short port = SERVER_DEFAULT_PORT;
	if (numArguments > 1)
	{
		// Convert port to short
		if (!FromString<unsigned short>(port, arguments[1], std::dec))
		{
			std::cout << "Cannot convert " << arguments[1] << " to a port number" << std::endl;
			return EXIT_FAILURE;
		}
	}

	GameServer server;
	server.Start(port);
	bool isRunning = true;
	while (isRunning)
	{
		std::cout << "Space Bomber > ";
		std::string input;
		std::cin >> input;

		if (input == "")
		{
		}
		else if (input == "quit")
		{
			isRunning = false;
			server.Stop();
			std::cout << "   " << "Quitting" << std::endl;
		}
		else if (input == "start")
		{
			if (!server.IsRunning())
			{
				if (server.Start(port))
				{
					std::cout << "   " << "Started server " << "on port " << port << std::endl;
				}
				else
				{
					std::cout << "   " << "Failed to start server. Maybe port not free?" << std::endl;
				}
			}
			else
			{
				std::cout << "   " << "Server already running with " << server.GetNumClients() << " connected players" << std::endl;
			}
		}
		else if (input == "stop")
		{
			server.Stop();
			std::cout << "   " << "Server stopped" << std::endl;
		}
		else if (input == "help")
		{
			std::cout << "   You can write start, stop, stat or quit!" << std::endl;
		}
		else if (input == "stat")
		{
			std::cout << "   "
				<< "Status: "
				<< "NumClients: " << server.GetNumClients()
				<< "   queueLen: " << server.GetGlobalChangeQueueLength()
				<< "   NextChange:" << server.GetNextChangeNumber()
				<< "   WorldTime: " << server.GetWorldTime()
				<< "   AvgPacketRx: " << ((float)(int)(server.avgNumPackets*100))/100.f
				<< std::endl;
		}
		else
		{
			std::cout << "   " << input << " not implemented" << std::endl << std::endl;
		}
	}

	return 0;
}
